package com.itchu.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchu.auth.config.JwtProperties;
import com.itchu.common.domain.BeanHelper;
import com.itchu.common.domain.PageResult;
import com.itchu.system.domain.SysRole;
import com.itchu.system.domain.SysUser;
import com.itchu.system.dto.SysUserDto;
import com.itchu.system.mapper.AuthorityMapper;
import com.itchu.system.mapper.SysRoleMapper;
import com.itchu.system.mapper.SysUserMapper;
import com.itchu.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AuthorityMapper authorityMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 查找系统用户的分页信息
     * @param key   搜索条件
     * @param page  当前页
     * @param rows  页大小
     * @param sortBy
     * @param desc
     * @return
     */
    @Override
    public PageResult<SysUser> findByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //开启分页
        PageHelper.startPage(page,rows);
        //创建一个封装条件的对象
        Example example = new Example(SysUser.class);
        if (!StringUtils.isEmpty(key)) {
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name","%" + key + "%");
            criteria.orLike("id","%" + key + "%");
        }
        if (!StringUtils.isEmpty(sortBy)) {
            example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
        }
        List<SysUser> sysUsers = sysUserMapper.selectByExample(example);
        PageInfo<SysUser> pageInfo = new PageInfo<>(sysUsers);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),sysUsers);
    }

    /**
     * 删除系统用户
     * @param id  系统用户id
     * @return
     */
    @Override
    public void deletSysUser(Long id) {
            sysUserMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改系统用户
     * @param sysUser  系统用户信息
     * @param rids  角色ids
     * @return
     */
    @Override
    public void updateSysUser(SysUser sysUser,List<Long> rids) {
        if (sysUser != null) {

            // 查询
            SysUser user = sysUserMapper.selectByPrimaryKey(sysUser.getId());
            if (!user.getPassword().equals(sysUser.getPassword())) {
                String oldPassword = sysUser.getPassword();
                String newPassword = passwordEncoder.encode(oldPassword);
                sysUser.setPassword(newPassword);
            }


            sysUser.setUpdateTime(new Date());
            sysUserMapper.updateByPrimaryKey(sysUser);
            if (!CollectionUtils.isEmpty(rids)) {
                roleMapper.deleteUserIdRoleId(sysUser.getId());
                roleMapper.addUserIdRoleId(sysUser.getId(), rids);
            }
        }
    }

    /**
     * 根据id查找系统用户
     * @param id  系统id
     * @return
     */
    @Override
    public SysUserDto findById(Long id) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
        SysUserDto userDto = null;
        if (sysUser != null) {
            userDto = BeanHelper.copyProperties(sysUser, SysUserDto.class);
            List<SysRole> list  = roleMapper.findRolesByRid(id);
            if (!CollectionUtils.isEmpty(list)) {
                userDto.setRoles(list);
            }
        }
        return userDto;
    }

    /**
     * 添加系统用户
     * @param sysUser  系统用户信息
     * @param rids  角色ids
     * @return
     */
    @Override
    public void addSysUser(SysUser sysUser, List<Long> rids) {
        if (sysUser != null) {
            //密码
            sysUser.setUpdateTime(new Date());
            sysUser.setCreateTime(new Date());
            sysUserMapper.insert(sysUser);
            if (!CollectionUtils.isEmpty(rids)) {
                roleMapper.deleteUserIdRoleId(sysUser.getId());
                roleMapper.addUserIdRoleId(sysUser.getId(),rids);
            }
        }
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return sysUserMapper.findByUserName(username);
    }
}